import { defineStore } from 'pinia'

export interface User {
  errCode: number
  newToken: string
  message:string
}

export const useAuthStore = defineStore('auth', () => {
  const user = ref<User | null>(null)
  const isLoggedIn = computed(() => !!user.value)

  const initAuth = () => {
    if (import.meta.client) {
      const storedUser = localStorage.getItem('user')
      if (storedUser) {
        try {
          user.value = JSON.parse(storedUser)
        } catch (error) {
          console.error('Failed to parse stored user data:', error)
          localStorage.removeItem('user')
        }
      }
    }
  }

  const login = (userData: User) => {
    user.value = userData
    if (import.meta.client) {
      localStorage.setItem('user', JSON.stringify(userData))
    }
  }

  const logout = () => {
    user.value = null
    if (import.meta.client) {
      localStorage.removeItem('user')
    }
  }

  const updateUser = (userData: Partial<User>) => {
    if (user.value) {
      user.value = { ...user.value, ...userData }
      if (import.meta.client) {
        localStorage.setItem('user', JSON.stringify(user.value))
      }
    }
  }

  return {
    user: readonly(user),
    isLoggedIn,
    initAuth,
    login,
    logout,
    updateUser
  }
})